package com.tsin.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsin.usercenter.mapper.UserMapper;
import com.tsin.usercenter.model.User;
import com.tsin.usercenter.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    List<Long> mainUserList = Arrays.asList(1L, 2L, 3L);

    @Scheduled(cron = "0 20 0 * * ?")
    public void doCacheRecommendUser() {
        //加锁
        RLock lock = redissonClient.getLock("youni:precachejob:lock");
        try {
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println(Thread.currentThread().getId()+" 服务器的定时任务成功开始执行");
                for (long id : mainUserList) {
                    String redisKey = String.format("youni:user:recommend:%s", id);
                    ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userList = userService.page(new Page<>(9999, 10), queryWrapper);
                    try {
                        stringObjectValueOperations.set(redisKey, userList, 172800000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis缓存数据发生错误", e);
                    }
                }

            }
        } catch (InterruptedException e) {
            log.error("redis缓存数据发生错误", e);
        }finally {
            //只能释放自己的锁
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
                System.out.println(Thread.currentThread().getId()+" 服务器的定时任务已完成并关闭分布式锁");
            }
        }


    }

}
